/*
 * Copyright 2013 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.scp.admin.support;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;

/**
 * 
 * 批量操作支持
 * 
 * @author 劳水生
 * @File MemberBean.java Date:2014-3-22 下午10:36:19 2014
 */
@Service("mybatisBatch")
public class MybatisBatch {

	@Resource
	private SqlSessionTemplate sqlSessionTemplate;

	public int insertBatch(String statement, List<?> list) {
		return this.insertBatch(statement, list, true);
	}

	/**
	 * <pre>
	 * 批量插入
	 * isRollback=true 表示需要往外抛异常，并影响外面回滚
	 * </pre>
	 * 
	 * @param statement
	 * @param list
	 * @param isRollback
	 * @return
	 */
	public int insertBatch(String statement, List<?> list, boolean isRollback) {
		SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
		int count = 0;
		try {
			if (list == null || list.isEmpty()) {
				return count;
			} else {
				for (Object obj : list) {
					count += session.insert(statement, obj);
				}
				session.commit();
				session.clearCache();
			}
		} catch (Exception e) {
			session.rollback();
			if (isRollback) {
				throw e;
			}
		} finally {
			session.close();
		}
		return count;
	}

	/**
	 * <pre>
	 * 批量修改
	 * isRollback=true 表示需要往外抛异常，并影响外面回滚
	 * </pre>
	 * 
	 * @param statement
	 * @param list
	 * @param isRollback
	 * @return
	 */
	public int updateBatch(String statement, List<?> list, boolean isRollback) {
		SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
		int count = 0;
		try {
			if (list == null || list.isEmpty()) {
				return count;
			} else {
				for (Object obj : list) {
					count += session.update(statement, obj);
				}
				session.commit();
				session.clearCache();
			}
		} catch (Exception e) {
			session.rollback();
			if (isRollback) {
				throw e;
			}
		} finally {
			session.close();
		}
		return count;
	}

}
